package com.wlyuan.open.remote.consumer;

import com.wlyuan.core.domain.event.DomainEventPublisher;
import com.wlyuan.open.domain.repository.PushTaskRepository;
import com.wlyuan.open.domain.repository.PushTenantRepository;
import com.wlyuan.open.infrastructure.event.OrderChanged;
import com.wlyuan.open.remote.converter.OrderMessageConverter;
import com.wlyuan.open.remote.message.OrderMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderDeviceBoundConsumer {

    private final OrderMessageConverter messageConverter = new OrderMessageConverter();
    private final PushTenantRepository pushTenantRepository;
    private final PushTaskRepository pushTaskRepository;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = "queue.open.pusher.order.bound"),
                    exchange = @Exchange(value = "exchange.topic.order"), key = "OrderDeviceBound")
    })
    public void receiveOrderCreated(String message) {
        logger.info("接到订单绑定设备消息：{}",message);
        OrderMessage orderSignedMessage = messageConverter.convert(message);
//        //判断租户id 是否在对接表中，如果存在，则将数据保存
//        Long tenantId = orderSignedMessage.getOrder().getTenantId();
//        var pushTenant = pushTenantRepository.ofTenantAndType(tenantId, PushBusinessType.ORDER_SIGNED);
//        if(pushTenant!=null){
//            PushTask pushTask = PushTaskAssembler.merge(orderSignedMessage.getOrder(),pushTenant);
//            pushTaskRepository.save(pushTask);
//        }
        //转发
        DomainEventPublisher.publish(new OrderChanged(orderSignedMessage.getOrder(),"OrderDeviceBound"));
    }
}
